package com.guava;

import com.google.common.util.concurrent.*;
import org.junit.Test;

import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executors;

/**
 * Created by user on 17/7/8.
 */
public class demo {

    @Test
    public void test(){
        listenableFutureWithCallbackExample();
    }

    public static void listenableFutureWithCallbackExample() {
        ListeningExecutorService executor = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1));

        Callable<String> asyncTask = new Callable<String>() {
            @Override
            public String call() throws Exception {
                Thread.sleep(10000);
                return "success";
            }
        };

        ListenableFuture<String> listenableFuture = executor.submit(asyncTask);

        Futures.addCallback(listenableFuture, new FutureCallback<String>() {
            public void onSuccess(String result) {
                //doMoreWithTheResultImmediately(result);
                System.out.println("doMoreWithTheResultImmediately");
            }

            public void onFailure(Throwable thrown) {
                System.out.println("fail");
            }
        });

        //doSomethingElse();
        System.out.println(11111);

        try {
            String result = listenableFuture.get();
            System.out.println("result "+result);
           // useResult(result);
        } catch (ExecutionException e) {
            //log.error("Task failed", e);
        } catch (InterruptedException e) {
            //log.warn("Task interrupted", e);
        }

        executor.shutdown();
    }
}
